package com.wei.frame.utils;

import android.app.Activity;

import androidx.annotation.Nullable;

import java.util.Stack;

/**
 * 作者：赵若位
 * 时间：2020/12/23 10:56
 * 祈祷：佛祖保佑，永无Bug~
 * 功能：Activity堆栈管理
 */
public final class AppManager {
    private static volatile AppManager sManager;
    private static Stack<Activity> sActivities;


    private AppManager() {
        sActivities = new Stack<>();
    }

    public static AppManager getInstance() {
        if (null == sManager) {
            synchronized (AppManager.class) {
                if (null == sManager) {
                    sManager = new AppManager();
                }
            }
        }
        return sManager;
    }

    /*Activity入栈*/
    public void add(@Nullable Activity activity) {
        if (null != activity) {
            sActivities.add(activity);
        }
    }

    /*获取栈顶的Activity*/
    public Activity getCurrent() {
        return sActivities.lastElement();
    }

    /*移除栈顶的Activity*/
    public void finishActivity() {
        Activity activity = sActivities.lastElement();
        finishActivity(activity);
    }

    /*移除指定的Activity*/
    public void finishActivity(Activity activity) {
        if (null != activity) {
            sActivities.remove(activity);
            activity.finish();
        }
    }

    /*移除堆栈中所有的Activity*/
    public void finishAllActivity() {
        synchronized (AppManager.class) {
            for (Activity activity : sActivities) {
                if (null != activity) {
                    activity.finish();
                }
            }
            sActivities.clear();
        }
    }


    /**
     * 退出应用程序
     * 此方法经测试在某些机型上并不能完全杀死 App 进程, 几乎试过市面上大部分杀死进程的方式, 但都发现没卵用, 所以此
     * 方法如果不能百分之百保证能杀死进程, 就不能贸然释放资源, 否则会造成其他问题, 如果您
     * 有测试通过的并能适用于绝大多数机型的杀死进程的方式, 望告知
     */
    public void exit() {
        try {
            finishAllActivity();
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
